package main

import (
	"fmt"
	"gitee.com/libbylg/pkgr/repo"
	"os"
)

type CmdExportOptions struct {
	Label  string
	Format string
}

// NewCmdListOptions 识别命令行选项.
// pkgr list [PATTERN] [--regex] [--plan PLAN-FILE] [--env ENV-NAME] [--devrepo|--pkgrepo] [--csv [SEP]]
func NewCmdExportOptions(argv []string) (*CmdExportOptions, error) {
	if len(argv) < 2 {
		return nil, fmt.Errorf("the required parameter is missing, try -h for help")
	}

	// 初始化默认值
	opt := &CmdExportOptions{
		Label:  "",
		Format: "",
	}

	// 读取选项
	for index := 2; index < len(argv); index++ {
		// 是否按照正则表达式的方式去匹配
		if argv[index] == "--table" {
			opt.Format = "table"
			continue
		}

		if argv[index] == "--json" {
			opt.Format = "json"
			continue
		}

		// 识别 PATTERN 参数
		if len(opt.Label) == 0 {
			opt.Label = argv[index]
			continue
		}

		return nil, fmt.Errorf("unsupported option `%v'", argv[index])
	}

	if opt.Label == "" {
		return nil, fmt.Errorf("no label specified")
	}

	if opt.Format == "" {
		opt.Format = "table"
	}

	if opt.Format == "table" || opt.Format == "json" {
		return nil, fmt.Errorf("unsupported format '%v'", opt.Format)
	}

	return opt, nil
}

// CmdExport 编码
// pkgr export LABEL [--table|--json]
func CmdExport(argv []string) int {
	if len(argv) != 3 {
		ERROR("Missing parameters, try -h help")
		return 1
	}

	opt, err := NewCmdExportOptions(argv)
	if err != nil {
		ERROR("Load option for `%v' failed: %v", "export", err.Error())
		return 1
	}

	// 检查下标签是否合法
	_, err = repo.ParseModuleLabel(opt.Label)
	if err != nil {
		ERROR("Invalid label `%v': %v", opt.Label, err.Error())
		return 1
	}

	// 读取模块描述信息
	versionDesc, err := repo.ReadModuleVersionDescription(opt.Label)
	if err != nil {
		ERROR("Load option for `%v' failed: %v", "export", err.Error())
		return 1
	}

	if opt.Format == "json" {
		result, err := repo.DumpToJson(versionDesc)
		if err != nil {
			ERROR("Generate json failed: %v", "export", err.Error())
			return 1
		}

		fmt.Fprintf(os.Stdout, "%v", result)
		return 0
	}

	if opt.Format == "table" {

	}

	return 0
}
